<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Chat Demo</title>
<link href="css/chat.css" rel="stylesheet">
<script src="js/jquery-1.6.2.js"></script>
<script src="js/socket.io.js"></script>
<script>
	// socket.io specific code
	var socket = io.connect("/chat");

	socket.on('connect', function() {
		$('#chat').addClass('connected');
	});

	socket.on('announcement', function(msg) {
		$('#lines').append($('<p>').append($('<em>').text(msg)));
	});

	socket.on('nicknames', function(nicknames) {
		$('#nicknames').empty().append($('<span>Online: </span>'));
		for ( var i in nicknames) {
			$('#nicknames').append($('<b>').text(nicknames[i]));
		}
	});

	socket.on('user message', message);
	socket.on('reconnect', function() {
		$('#lines').remove();
		message('System', 'Reconnected to the server');
	});

	socket.on('reconnecting', function() {
		message('System', 'Attempting to re-connect to the server');
	});

	socket.on('error', function(e) {
		message('System', e ? e : 'A unknown error occurred');
	});

	function message(from, msg) {
		$('#lines').append($('<p>').append($('<b>').text(from), msg));
	}

	// dom manipulation
	$(function() {
		$('#set-nickname').submit(function(ev) {
			socket.emit('nickname', $('#nick').val(), function(set) {
				if (!set) {
					clear();
					return $('#chat').addClass('nickname-set');
				}
				$('#nickname-err').css('visibility', 'visible');
			});
			return false;
		});

		$('#send-message').submit(function() {
			message('me', $('#message').val());
			socket.emit('user message', $('#message').val());
			clear();
			$('#lines').get(0).scrollTop = 10000000;
			return false;
		});

		function clear() {
			$('#message').val('').focus();
		}
		;
	});
</script>
</head>
<body>
	<div id="chat">
		<div id="nickname">
			<form id="set-nickname" class="wrap">
				<p>Please type in your nickname and press enter.</p>
				<input id="nick">
				<p id="nickname-err">Nickname already in use</p>
			</form>
		</div>
		<div id="connecting">
			<div class="wrap">Connecting to socket.io server</div>
		</div>
		<div id="messages">
			<div id="nicknames"></div>
			<div id="lines"></div>
		</div>
		<form id="send-message">
			<input id="message">
			<button>Send</button>
		</form>
	</div>
</body>
</html>